package com.kongge.formlike.service.rule;

import android.text.TextUtils;

import com.kongge.formlike.util.ProtocolContants;

import java.util.HashMap;
import java.util.Map;

/**
 * author:kongge
 * date:2018/7/21
 * layout:
 * description:
 */

public class RuleFactory {

    private static final Map<String, Class> ruleMap = new HashMap<>();

    static {
        ruleMap.put(ProtocolContants.STR_NOTNULL, RuleNotNull.class);
        ruleMap.put(ProtocolContants.STR_LENGTH, RuleLength.class);
        ruleMap.put(ProtocolContants.STR_MINLENGTH, RuleMinLength.class);
        ruleMap.put(ProtocolContants.STR_MAXLENGTH, RuleMaxLength.class);
        ruleMap.put(ProtocolContants.STR_TEXTMATCH, RuleTextMatch.class);
    }

    public static IRule getRule(String type) {
        if (TextUtils.isEmpty(type)) {
            return null;
        }
        IRule rule = null;
        Class c = ruleMap.get(type);
        if (c != null) {
            try {
                rule = (IRule) c.newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return rule;
    }

    public static void addRule(String ruleName, Class c) {
        if (!TextUtils.isEmpty(ruleName) && c != null) {
            ruleMap.put(ruleName, c);
        }
    }
}
